package com.google.code.p.restrpc.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.code.p.restrpc.DefaultRpcResponse;
import com.google.code.p.restrpc.RpcFault;
import com.google.code.p.restrpc.Shutdownable;
import com.google.code.p.restrpc.core.async.AsyncServiceManagers;

public class RestRpcFilter implements Filter {
    
    private static final Log logger = LogFactory.getLog(RestRpcFilter.class);
    
    private String urlContext = "/restrpc";
    
    private RpcServiceDispatcher dispatcher;
    
    public void init(FilterConfig filterConfig) throws ServletException {
        String contextUrl = filterConfig.getInitParameter("urlContext");
        if (StringUtils.isNotEmpty(contextUrl)) {
            this.urlContext = contextUrl;
        }
        
        // try to resolve the bean definition in spring context
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        if (webApplicationContext != null) {
            try {
                dispatcher = webApplicationContext.getBean(RpcServiceDispatcher.class);
                if (dispatcher instanceof UrlContextAware) {
                    ((UrlContextAware) dispatcher).setUrlContext(this.urlContext);
                }
            }
            catch (BeansException e) {
            }
        }
        
        // if not found , create default instance.
        if (dispatcher == null) {
            DefaultRpcServiceDispatcher dispatcher = new DefaultRpcServiceDispatcher(this.urlContext);
            dispatcher.setAsyncServiceManager(AsyncServiceManagers.getAsyncRpcManager());
            this.dispatcher = dispatcher;
        }
    }
    
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException,
                                           ServletException {
        
        if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRequest");
        }
        
        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        try {
            dispatcher.dispatch(httpRequest, httpResponse);
            response.getOutputStream().flush();
        }
        catch (Throwable e) {
            logger.error(e, e);
            
            DefaultRpcResponse rpcResponse = new DefaultRpcResponse();
            rpcResponse.setSucceed(false);
            RpcFault fault = new RpcFault();
            if (e.getCause() != null) {
                fault.setMessage(e.getMessage() + " Caused : "
                                 + e.getCause().getMessage());
            }
            else {
                fault.setMessage(e.getMessage());
            }
            rpcResponse.setFault(fault);
            
            httpResponse.setHeader("CONTENT-TYPE", "text/json");
            httpResponse.getOutputStream()
                        .print(JSON.toJSONString(rpcResponse,
                                                 SerializerFeature.WriteClassName));
            httpResponse.getOutputStream().flush();
        }
    }
    
    public void destroy() {
        if (dispatcher instanceof Shutdownable) {
            ((Shutdownable) dispatcher).shutdown();
        }
    }
    
}
